// vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 foldmethod=marker:

function change_science(p) {
  if (!confirm('Do you really want change science status?')) return;

  $.post('http://www1.astrowars.com/0/Science/submit.php',
         {science: p},
         function() { window.location = "/0/Science/" }
        );
}

// {{{ Plugin jQuery addmenu(text, url)
function findPos(obj) {
  if (!obj) return false;
  var curleft = obj.offsetLeft || 0;
  var curtop = obj.offsetTop || 0;
  var curheight = obj.offsetHeight || 0;
  var curwidth = obj.offsetWidth || 0;

  while (obj = obj.offsetParent) {
    curleft += obj.offsetLeft
    curtop += obj.offsetTop
  }
  return {x:curleft,y:curtop,w:curwidth,h:curheight};
}

var menuplus_timer = new Array();

jQuery.fn.addmenu = function (text, url) {
  return this.each(function() {
    var m_id = 'awmp_'+this.id;

    if ($('#'+m_id).size() == 0) {
      var awmp_html = '<div id="'+m_id+'"></div>';
      $('body').append(awmp_html);

      var m_pos = findPos(this);
      var m_css = {
        position: 'absolute',
        top: m_pos.y + m_pos.h,
        left: m_pos.x,
        'min-width': m_pos.w,
        border:"1px solid #1f1f1f",
        background: '#404040',
        color: '#ffffff',
        'font-family':'verdana',
        'font-size': '12px'
      }

      $('#'+m_id)
        .addClass('awmp')
        .css(m_css)
        .hide()
        .hover(
          function() {
            if (menuplus_timer[m_id]) clearTimeout(menuplus_timer[m_id]);
          },
          function() { $('#'+m_id).hide(0); }
        );

      $(this).hover(
        function() { $('#'+m_id).show(0); },
        function() {
          var t=setTimeout(function() {
            $('#'+m_id).hide(0);
            delete menuplus_timer[m_id];
            }, 200);
          menuplus_timer[m_id] = t;
        }
      );
    }

    var id = '_'+$('#'+m_id+' a').size();
    var html = '<a id="'+m_id+id+'" href="javascript:void(0);" class="awmp_item">'+text+'</a>';
    $('#'+m_id).append(html);

    if (typeof url == "function") $('#'+m_id+id).click(url);
    else $('#'+m_id+id).attr('href', url);
  });
}
/// }}}
// {{{ Plugin jQuery cookie
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// }}}

function ap_showNewsCV (context) {
  //Style for news cv
  $('style:last').after('<style>.ap_news_cv { float: right; margin: 5px; padding: 5px; border: 1px solid #aaaaaa; background-color: #444444; }</style>');
  
  $('td:contains(going to attack)', context).each(function(i) {
    var tmp;
    var rs = $(this).html().match(/(\d+ \w{2})/g);
    var cv = 0;
    for(var i = 0; i < rs.length; i++) {
      tmp = rs[i].match(/(\d+) (\w{2})$/);
      switch (tmp[2]) {
        case 'De': cv += 3 * parseInt(tmp[1]); break;
        case 'Cr': cv += 24 * parseInt(tmp[1]); break;
        case 'Ba': cv += 60 * parseInt(tmp[1]); break;
      }
    }
    $(this).prepend('<div align=center id="ap_news_cv_'+i+'" class="ap_news_cv"><small>Combat Value</small><br/><big><strong>'+cv+'</strong></big></div>');
  });
}

$(document).ready(function() {

  // {{{ Ajax loading
  $('body').append('<div id="aploading"></div>');
  $('#aploading').hide().css({
      'background': 'red',
      'color': 'white',
      'font-size': '11px',
      'padding': '3px',
      'position': 'absolute',
      'top': '0px',
      'right': '0px'
    }).text('loading...');

  $().ajaxStart(function() { $('#aploading').show(); });
  $().ajaxStop(function() { $('#aploading').hide(); });
  // }}}
  // {{{ Basic
  $('table[@width=600]:eq(0)').attr('id', 'awplus_navbar').find('tr td a').each(function(i) {
    var o = this.parentNode;
    switch (i) {
      case 0: o.id = 'astrowars'; return;
      case 1: o.id = 'news'; return;
      case 2: o.id = 'map'; return;
      case 3: o.id = 'planets'; return;
      case 4: o.id = 'science'; return;
    }

    if (this.innerHTML.match(/Trade/)) { o.id = 'trade'; return; }
    if (this.innerHTML.match(/Alliance/)) { o.id = 'alliance'; return; }

    o.id = 'fleet';
  });

  // Adding awplus logo
  $('#astrowars a b').html('AW');
  $('#astrowars').append(' + <a id="astrowars_awplus" href=\'http://code.google.com/p/awplus/\' target=\'_blank\'>awPlus</a>');
  
  // Id of content table
  $('table[@width=600]:eq(1)').attr('id', 'awplus_content')

  $('style').after('<style>.awmp_item { display: block; margin:0px; padding: 3px; }</style>');
  
  // }}}
  // {{{ Menu itens

  $('#news').addmenu('Forums', 'http://www.astrowars.com/forums/')
            .addmenu('Portal', 'http://www.astrowars.com/portal/Main_Page')
            .addmenu('Inbox', 'http://www.astrowars.com/forums/privmsg.php?folder=inbox')
            .addmenu('Rankings', 'http://www1.astrowars.com/rankings/')
            .addmenu('Settings', '/0/News/Settings.php')
            .addmenu('Logout', '/0/News/Logout.php');

  $('#map a').attr('href', '/0/Map/Coordinates.php');

  $('#planets').addmenu('Buildings', '/0/Planets/Buildings.php')
               .addmenu('Spend All PP in Trade', function(){
    if (!confirm('Do you really want spend all points in astrodollars?')) return;
    
    $.get('/0/Planets/submitall.php?produktion=trade', function() {window.location = "/0/Planets/"});
  });
  var plist = $.cookie('ap_planetlist');
  if (plist) {
    var l = plist.split('|');
    var t, t2;

    t2 = window.location.href.match(/\/0\/Planets\/Detail.php\/\?i=([0-9]+)$/);
    
    for (i in l) {
      t = l[i].split(':');
      if (t2 && t2[1] == t[0]) {
        t[1] = '<b>'+t[1]+'</b>';
      }
      $('#planets').addmenu(t[1], '/0/Planets/Detail.php/?i='+t[0]);
    }
  }

  $('#trade').addmenu('Agreements', '/0/Trade/Agreement.php')
             .addmenu('Artifacts', '/0/Trade/Artifacts.php')
             .addmenu('Sell', '/0/Trade/Sell.php')
             .addmenu('Buy', '/0/Trade/Buy.php');

  $('#alliance').addmenu('List', '/0/Alliance/List.php')
                .addmenu('NAPs', '/0/Alliance/NAP.php');

  $('#science')
    .addmenu('Change to Biology', function() { change_science('f_bio'); })
    .addmenu('Change to Economy', function() { change_science('f_eco'); })
    .addmenu('Change to Energy', function() { change_science('f_energy'); })
    .addmenu('Change to Mathematics', function() { change_science('f_math'); })
    .addmenu('Change to Physics', function() { change_science('f_physics'); })
    .addmenu('Change to Social', function() { change_science('f_social'); });

  // }}}

});
